﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMA.SGDB.BLL;
using DMA.SGDB.DAL;
using DMA.SGDB.Util;
using DMA.SGDB.Util.SGDBEnum;
using DMA.SGDB.Web.Shared;
using System.Data;

namespace DMA.SGDB.Web
{
    public partial class TelaCadastroClientes : System.Web.UI.Page
    {
        ClientePFBLL clientePFBll;
        ClientePJBLL clientePJBll;  
        CLIENTES_PF clientePF;
        CLIENTES_PJ clientePJ;      

        protected void Page_Load(object sender, EventArgs e)
        {
            pnlQuestion.Click += new EventHandler<Shared.CustomEventArgs.PainelYesNoUserEventArgs>(pnlQuestion_Click);

            if (!IsPostBack)
            {
                rdbPessoaFisica_CheckedChanged(null, null);
                SetMode(Crud.Options);
                ShowScreenOptions();
            }           
        }

        public void FillGridView(String TipoPessoa)
        {
            try
            {
                if (TipoPessoa.Equals("PessoaFisica"))
                {
                    DataTable table = new ClientePFBLL().GetAll();

                    gvList.DataSource = table;
                    gvList.DataBind();

                    if (table.Rows.Count > 0)
                        GridViewManager.Configure(gvList, table.Columns.Count + 2, new int[] { 1, 11 });
                }
                else if (TipoPessoa.Equals("PessoaJuridica"))
                {
                    DataTable table = new ClientePJBLL().GetAll();

                    gvList.DataSource = table;
                    gvList.DataBind();

                    if (table.Rows.Count > 0)
                        GridViewManager.Configure(gvList, table.Columns.Count + 2, new int[] { 1, 11 });
                }                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SetMode(Crud crud)
        {
            Session["Mode"] = crud;
            ToolBar(crud);
        }

        public void ToolBar(Crud crud)
        {
            switch (crud)
            {
                case Crud.List:
                    divBtnNew.Visible = true;
                    divBtnSave.Visible = false;
                    divBtnCancel.Visible = false;
                    divBtnBack.Visible = false;
                    break;
                case Crud.New:
                    divBtnNew.Visible = false;
                    divBtnSave.Visible = true;
                    divBtnCancel.Visible = true;
                    divBtnBack.Visible = false;
                    break;
                case Crud.Edit:
                    divBtnNew.Visible = false;
                    divBtnSave.Visible = true;
                    divBtnCancel.Visible = true;
                    divBtnBack.Visible = false;
                    break;
                case Crud.View:
                    divBtnNew.Visible = false;
                    divBtnSave.Visible = false;
                    divBtnCancel.Visible = false;
                    divBtnBack.Visible = true;
                    break;
                case Crud.Options:
                    divBtnNew.Visible = false;
                    divBtnSave.Visible = false;
                    divBtnCancel.Visible = false;
                    divBtnBack.Visible = false;
                    break;
            }
        }

        public Crud GetMode()
        {
            return (Crud)Session["Mode"];
        }

        public void SetId(int id)
        {
            Session["ID"] = id;
        }

        public int GetID()
        {
            return (int)Session["ID"];
        }
        
        protected void rdbPessoaFisica_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbPessoaFisica.Checked)
            {
                nome.Visible = true;
                cpf.Visible = true;
                sexo.Visible = true;                
                
                lblData.Text = "Data de Nascimento:";

                razaoSocial.Visible = false;
                nomeFantasia.Visible = false;
                cnpj.Visible = false;
                responsavel.Visible = false;

                rdbPessoaJuridica.Checked = false;
            }
            else if (rdbPessoaJuridica.Checked)
            {
                nome.Visible = false;
                cpf.Visible = false;
                sexo.Visible = false;

                lblData.Text = "Data de Fundação:";

                razaoSocial.Visible = true;
                nomeFantasia.Visible = true;
                cnpj.Visible = true;
                responsavel.Visible = true;
            }
        }

        protected void rdbPessoaJuridica_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbPessoaFisica.Checked)
            {
                rdbPessoaFisica.Checked = false;
                rdbPessoaFisica_CheckedChanged(null, null);
            }
            else if (rdbPessoaJuridica.Checked)
            {
                nome.Visible = false;
                cpf.Visible = false;
                sexo.Visible = false;

                lblData.Text = "Data de Fundação:";

                razaoSocial.Visible = true;
                nomeFantasia.Visible = true;
                cnpj.Visible = true;
                responsavel.Visible = true;
            }
        }
        
        protected void rdbFeminino_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbFeminino.Checked)
                rdbMasculino.Checked = false;
        }

        protected void rdbMasculino_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbMasculino.Checked)
                rdbFeminino.Checked = false;
        }

        protected void imgBtnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                SetMode(Crud.New);
                ShowScreenRegister();
                txtName.Focus();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void imgBtnCancel_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                RehabilitateFields();
                ShowScreenList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void Save()
        {
            try
            {
                SetValues();

                bool errorExist = true;

                if (Session["TipoPessoa"].ToString().Equals("PessoaFisica"))
                {
                    errorExist = GetValidationErrorMessages(clientePF);
                }
                else if (Session["TipoPessoa"].ToString().Equals("PessoaJuridica"))
                {
                    errorExist = GetValidationErrorMessages(clientePJ);
                }                

                if (errorExist == false)
                {
                    if (Crud.New.Equals(GetMode()))
                    {
                        if (rdbPessoaFisica.Checked == true)
                        {
                            clientePFBll = new ClientePFBLL();
                            clientePFBll.Insert(clientePF);
                        }
                        else
                        {
                            clientePJBll = new ClientePJBLL();
                            clientePJBll.Insert(clientePJ);
                        }
                        
                    }
                    if (Crud.Edit.Equals(GetMode()))
                    {
                        if (rdbPessoaFisica.Checked == true)
                        {
                            clientePFBll = new ClientePFBLL();
                            clientePFBll.Update(clientePF);
                        }
                        else
                        {
                            clientePJBll = new ClientePJBLL();
                            clientePJBll.Update(clientePJ);
                        }
                    }

                    FillGridView(Session["TipoPessoa"].ToString());
                    ShowScreenList();
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SetValues()
        {
            if (rdbPessoaFisica.Checked == true)
            {
                clientePF = new CLIENTES_PF();

                if (GetMode() == Crud.Edit)
                    clientePF.COD_CLI = GetID();

                clientePF.VIP_CLI = chkVIP.Checked ? (short)ClienteVIP.Sim : (short)ClienteVIP.Nao;

                clientePF.NOME_CLI = txtName.Text;
                clientePF.CPF_CLI = txtCPF.Text;
                clientePF.DTA_NSC_CLI = string.IsNullOrEmpty(txtData.Text) ? DateTime.Parse("01/01/1500") : DateTime.Parse(txtData.Text);
                clientePF.SEXO_CLI = rdbFeminino.Checked ? (short)Sexo.Feminino : (short)Sexo.Masculino;
                clientePF.TEL_CLI = txtTelefone.Text;
                clientePF.END_CLI = txtEndereco.Text;
                clientePF.CEP_CLI = txtCEP.Text;
                clientePF.CID_CLI = txtCidade.Text;
                clientePF.EMAIL_CLI = txtEmail.Text;

                clientePF.DTA_CLI = DateTime.Now;
            }
            else
            {
                clientePJ = new CLIENTES_PJ();

                if (GetMode() == Crud.Edit)
                    clientePJ.COD_CLI = GetID();

                clientePJ.VIP_CLI = chkVIP.Checked ? (short)ClienteVIP.Sim : (short)ClienteVIP.Nao;

                clientePJ.RAZAO_CLI = txtRazaoSocial.Text;
                clientePJ.NOME_CLI = txtNomeFantasia.Text;
                clientePJ.CNPJ_CLI = txtCNPJ.Text;
                clientePJ.DTA_NSC_CLI = DateTime.Parse(txtData.Text);
                clientePJ.TEL_CLI = txtTelefone.Text;
                clientePJ.END_CLI = txtEndereco.Text;
                clientePJ.CEP_CLI = txtCEP.Text;
                clientePJ.CID_CLI = txtCidade.Text;
                clientePJ.EMAIL_CLI = txtEmail.Text;
                clientePJ.RES_CLI = txtResponsavel.Text;

                clientePJ.DTA_CLI = DateTime.Now;
            }
        }
        
        protected void imgBtnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                SetMode(Crud.Edit);

                ShowScreenRegister();

                txtName.Focus();

                ImageButton img = (ImageButton)sender;
                GridViewRow row = (GridViewRow)img.Parent.Parent;

                int idRecordSelected = int.Parse(row.Cells[1].Text);

                SetId(idRecordSelected);

                PopulateFieldsWithDataDbconfig(idRecordSelected);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void imgBtnVisualize_Click(object sender, EventArgs e)
        {
            try
            {
                SetMode(Crud.View);

                ShowScreenRegister();               

                ImageButton img = (ImageButton)sender;
                GridViewRow row = (GridViewRow)img.Parent.Parent;

                var idRecordSelected = row.Cells[1].Text;

                SetId(int.Parse(idRecordSelected));

                PopulateFieldsWithDataDbconfig(int.Parse(idRecordSelected));

                MakeFieldsReadOnly();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void imgBtnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                ImageButton img = (ImageButton)sender;
                GridViewRow row = (GridViewRow)img.Parent.Parent;

                pnlList.Visible = false;
                divBtnNew.Visible = false;
                
                pnlQuestion.Value = row.Cells[1].Text;
                pnlQuestion.Message = "Confirma a exclusão do Cliente " + row.Cells[2].Text + "?";
                pnlQuestion.ShowPainelQuestion();                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void pnlQuestion_Click(object sender, Shared.CustomEventArgs.PainelYesNoUserEventArgs e)
        {
            try
            {
                if (e.Result == Shared.CustomEventArgs.Result.Yes)
                {
                    if (Session["TipoPessoa"].ToString().Equals("PessoaFisica"))
                    {
                        clientePFBll = new ClientePFBLL();
                        

                        clientePFBll.Delete(int.Parse(e.Value.ToString()));                        
                    }
                    else if (Session["TipoPessoa"].ToString().Equals("PessoaJuridica"))
                    {
                        clientePJBll = new ClientePJBLL();

                        clientePJBll.Delete(int.Parse(e.Value.ToString()));
                    }

                    FillGridView(Session["TipoPessoa"].ToString());
                    ShowScreenList();
                }

                divBtnNew.Visible = true;
                pnlList.Visible = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void PopulateFieldsWithDataDbconfig(int idRecordSelected)
        {
            try
            {
                if (Session["TipoPessoa"].ToString().Equals("PessoaFisica"))
                {
                    clientePF = new CLIENTES_PF();

                    clientePF = new ClientePFBLL().LoadById(GetID());
                    
                    rdbPessoaFisica.Checked = true;
                    rdbPessoaFisica_CheckedChanged(null, null);

                    if (clientePF.VIP_CLI == (short)ClienteVIP.Sim)
                        chkVIP.Checked = true;

                    txtName.Text = clientePF.NOME_CLI;
                    txtCPF.Text = clientePF.CPF_CLI.ToString();
                    txtData.Text = clientePF.DTA_NSC_CLI.ToString();

                    if (clientePF.SEXO_CLI == (short)Sexo.Feminino)
                        rdbFeminino.Checked = true;
                    else
                        rdbMasculino.Checked = true;

                    txtTelefone.Text = clientePF.TEL_CLI;
                    txtEndereco.Text = clientePF.END_CLI;
                    txtCEP.Text = clientePF.CEP_CLI;
                    txtCidade.Text = clientePF.CID_CLI;
                    txtEmail.Text = clientePF.EMAIL_CLI;
                }
                else
                {
                    clientePJ = new CLIENTES_PJ();

                    clientePJ = new ClientePJBLL().LoadById(GetID());

                    rdbPessoaJuridica.Checked = true;
                    rdbPessoaFisica_CheckedChanged(null, null);

                    if (clientePJ.VIP_CLI == (short)ClienteVIP.Sim)
                        chkVIP.Checked = true;

                    txtRazaoSocial.Text = clientePJ.RAZAO_CLI;
                    txtNomeFantasia.Text = clientePJ.NOME_CLI;
                    txtCNPJ.Text = clientePJ.CNPJ_CLI.ToString();
                    txtData.Text = clientePJ.DTA_NSC_CLI.ToString();
                    txtTelefone.Text = clientePJ.TEL_CLI;
                    txtEndereco.Text = clientePJ.END_CLI;
                    txtCEP.Text = clientePJ.CEP_CLI;
                    txtCidade.Text = clientePJ.CID_CLI;
                    txtEmail.Text = clientePJ.EMAIL_CLI;
                    txtResponsavel.Text = clientePJ.RES_CLI;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool GetValidationErrorMessages(CLIENTES_PF clientePF)
        {
            clientePFBll = new ClientePFBLL();

            List<string> errosList = new List<string>();

            List<String> strEmptyFields = clientePFBll.ValidateFields(clientePF);

            if (strEmptyFields != null)
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Warning;
                pnlErros.Message = "Pêndencia(s):";

                foreach (String erro in strEmptyFields)
                {
                    errosList.Add(erro);
                }
            }
            else if (!clientePFBll.ValidateCPF(clientePF.CPF_CLI.ToString()))
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Error;
                pnlErros.Message = "Erro:";

                errosList.Add("CPF Inválido!");
            }
            else
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Error;
                pnlErros.Message = "Erro:";

                String isDuplicateRecord = clientePFBll.GetDuplicateRecord(clientePF);

                if (!string.IsNullOrEmpty(isDuplicateRecord))
                    errosList.Add(isDuplicateRecord);
            }

            if (errosList.Count > 0)
            {
                pnlErros.ErrorList = errosList;
                pnlErros.ShowPainelErrors();

                return true;
            }
            else
                return false;
        }

        public bool GetValidationErrorMessages(CLIENTES_PJ clientePJ)
        {
            clientePJBll = new ClientePJBLL();

            List<string> errosList = new List<string>();

            List<String> strEmptyFields = clientePJBll.ValidateFields(clientePJ);

            if (strEmptyFields != null)
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Warning;
                pnlErros.Message = "Pêndencia(s):";

                foreach (String erro in strEmptyFields)
                {
                    errosList.Add(erro);
                }
            }
            else if (clientePJBll.ValidateCNPJ(clientePJ.CNPJ_CLI.ToString()))
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Error;
                pnlErros.Message = "Erro:";

                errosList.Add("CNPJ Inválido!");
            }
            else
            {
                pnlErros.TypeMessage = Shared.UserControl.TypeMessage.Error;
                pnlErros.Message = "Erro:";

                String isDuplicateRecord = clientePJBll.GetDuplicateRecord(clientePJ);

                if (!string.IsNullOrEmpty(isDuplicateRecord))
                    errosList.Add(isDuplicateRecord);
            }

            if (errosList.Count > 0)
            {
                pnlErros.ErrorList = errosList;
                pnlErros.ShowPainelErrors();

                return true;
            }
            else
                return false;
        }

        public void MakeFieldsReadOnly()
        {
            txtName.ReadOnly = true;
            rdbPessoaFisica.Enabled = false;
            chkVIP.Enabled = false;
            txtCPF.ReadOnly = true;
            txtData.ReadOnly = true;
            rdbFeminino.Enabled = false;
            rdbMasculino.Enabled = false;
            txtTelefone.ReadOnly = true;
            txtEndereco.ReadOnly = true;
            txtCEP.ReadOnly = true;
            txtCidade.ReadOnly = true;
            txtEmail.ReadOnly = true;
            txtRazaoSocial.ReadOnly = true;
            txtNomeFantasia.ReadOnly = true;
            txtCNPJ.ReadOnly = true;
            txtResponsavel.ReadOnly = true;
        }

        public void RehabilitateFields()
        {
            txtName.ReadOnly = false;
            rdbPessoaFisica.Enabled = true;
            chkVIP.Enabled = true;
            txtCPF.ReadOnly = false;
            txtData.ReadOnly = false;
            rdbFeminino.Enabled = true;
            rdbMasculino.Enabled = true;
            txtTelefone.ReadOnly = false;
            txtEndereco.ReadOnly = false;
            txtCEP.ReadOnly = false;
            txtCidade.ReadOnly = false;
            txtEmail.ReadOnly = false;
            txtRazaoSocial.ReadOnly = false;
            txtNomeFantasia.ReadOnly = false;
            txtCNPJ.ReadOnly = false;
            txtResponsavel.ReadOnly = false;
        }


        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvList.PageIndex = e.NewPageIndex;
                FillGridView(Session["TipoPessoa"].ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ShowScreenRegister()
        {
            ClearAllFields(pnlRegister);
            pnlList.Visible = false;
            pnlRegister.Visible = true;
            pnlOptions.Visible = false;
            rdbFeminino.Checked = true;

            if (Session["TipoPessoa"].ToString().Equals("PessoaFisica"))
            {
                rdbPessoaFisica.Checked = true;
                rdbPessoaFisica_CheckedChanged(null, null);
            }
            else if (Session["TipoPessoa"].ToString().Equals("PessoaJuridica"))
            {
                rdbPessoaJuridica.Checked = true;
                rdbPessoaFisica_CheckedChanged(null, null);
            }
        }

        public void ShowScreenList()
        {
            SetMode(Crud.List);
            pnlList.Visible = true;
            pnlRegister.Visible = false;
            pnlOptions.Visible = false;
        }

        public void ShowScreenOptions()
        {
            SetMode(Crud.Options);
            pnlList.Visible = false;
            pnlRegister.Visible = false;
            pnlOptions.Visible = true;
        }

        public void ClearAllFields(System.Web.UI.Control controle)
        {
            foreach (System.Web.UI.Control ctle in controle.Controls)
            {
                if (ctle is System.Web.UI.WebControls.TextBox)
                {
                    ((System.Web.UI.WebControls.TextBox)ctle).Text = string.Empty;
                }
                else if (ctle is DropDownList)
                {
                    ((DropDownList)ctle).SelectedValue = "-1";
                }
                else if (ctle is CheckBoxList)
                {
                    foreach (ListItem checkBox in ((CheckBoxList)ctle).Items)
                    {
                        checkBox.Selected = false;
                    }
                }
                else if (ctle is CheckBox)
                {
                    ((CheckBox)ctle).Checked = false;
                }
                else if (ctle.Controls.Count > 0)
                {
                    ClearAllFields(ctle);
                }
            }
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            FillGridView(Session["TipoPessoa"].ToString());
        }

        protected void lbtPessoaFisica_Click(object sender, EventArgs e)
        {
            Session["TipoPessoa"] = "PessoaFisica";
            FillGridView(Session["TipoPessoa"].ToString());
            ShowScreenList();
        }

        protected void lbtPessoaJuridica_Click(object sender, EventArgs e)
        {
            Session["TipoPessoa"] = "PessoaJuridica";
            FillGridView(Session["TipoPessoa"].ToString());            
            ShowScreenList();
        }

        protected void lbtBack_Click(object sender, EventArgs e)
        {
            ShowScreenOptions();
        }
    }
}